package config

import (
	"encoding/json"
	"log"
	"os"
	"training-camp/week4/errors"
)

type AppConfig struct {
	Addr           string
	ReadTimeout    int
	WriteTimeout   int
	MaxHeaderBytes int
}
type Config struct {
	Data map[string]AppConfig
}

func New(file string) *Config {
	config := &Config{}
	err := config.loadConfig(file)
	if err != nil {
		panic(err)
	}
	return config
}
func (c *Config) loadConfig(file string) error {
	f, err := os.Open(file)
	defer f.Close()
	if err != nil {
		log.Println("open file err = ", err)
		return err
	}
	c.Data = make(map[string]AppConfig)
	decoder := json.NewDecoder(f)
	err = decoder.Decode(&c.Data)
	if err != nil {
		return err
	}
	log.Println("json read done well")
	return nil
}
func (c *Config) GetAppConfig(app string) (*AppConfig, error) {
	if c.Data == nil {
		err := errors.New(20001, "configGetError", "Config unload")
		return nil, err
	}
	if config, ok := c.Data[app]; ok {
		return &config, nil
	}
	return nil, errors.New(20001, "configGetError", app+" config can't find")
}
